﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using EIS.DatabaseHelper;
using EIS.Obj;
using EIS.ServerAdapter;

namespace EIS.Data
{
    public class FunctionSchema
    {
        private string[] columnNames;
        public readonly DataSet DsSchema;
        private string functionID;
        public string SchemaTableName;
        private string layoutTableName;
        private string functionDataTableName;
        private string functionStatusTableName;

        public FunctionSchema(string id)
        {
            functionID = id;
            SchemaTableName = EISConstant.GetSchemaTableName(functionID);
            layoutTableName = EISConstant.GetLayoutTableName(functionID);
            functionStatusTableName = EISConstant.GetStatusTableName(functionID);
            functionDataTableName = id;
            DsSchema = RestAdapter.HttpGet(GlobalVariable.Instance.ServerRootURL + "functionSchema/" + id + @"/" + GlobalVariable.Instance.CurrentToken);

            if (DsSchema.Tables[0].TableName.ToUpper() == "ERROR")
            {
                throw new Exception(DsSchema.Tables[0].Rows[0]["errorCode"].ToString() + DsSchema.Tables[0].Rows[0]["errorMessage"].ToString());
            }
            GetColumnNames();
            SaveSchema();
            AlterFunctionDataTable();
            AlterFunctionStatusTable();
            ProvideDefaultLayout();
        }

        private void GetColumnNames()
        {
            columnNames = new string[DsSchema.Tables[0].Rows.Count];
            int index = columnNames.Length;

            for(int i = 0; i< index; i++)
            {
                columnNames[i] = DsSchema.Tables[0].Rows[i]["FieldName"].ToString().Trim();
            }
        }

        public string[] ColumnNames()
        {
            return columnNames;
        }

        public DataSet GetSchema()
        {
            return DsSchema;
        }

        public void SaveSchema()
        {
            var dBHandler = new DBHandler();
            dBHandler.DeleteAllRecordsInTable(SchemaTableName);

            var dsToSave = dBHandler.GetEmptyDataSet(SchemaTableName);

            foreach (DataRow drSchema in DsSchema.Tables[0].Rows)
            {
                var dr = dsToSave.Tables[0].NewRow();
                dr[0] = drSchema["FieldName"];
                dr[1] = drSchema["DisplayName"];

                dsToSave.Tables[0].Rows.Add(dr);
            }
            dBHandler.InsertRecords(SchemaTableName, dsToSave.Tables[0]);
        }

        private void AlterFunctionDataTable()
        {
            var dBHandler = new DBHandler();
            string[] currentColumn = dBHandler.GetCurrentTableColumns(functionDataTableName);
            string[] serverColumn = columnNames;
            var columnsToAdd = new List<FunctionDataTableColumn>();

            foreach (var colName in serverColumn)
            {
                if (currentColumn.Contains(colName.Trim())) continue;
                FunctionDataTableColumn colToAdd = null;
                foreach (DataRow dr in DsSchema.Tables[0].Rows)
                {
                    if ((string)dr["FieldName"] == colName.Trim())
                    {
                        colToAdd = new FunctionDataTableColumn(colName.Trim(), dr["Type"].ToString(), Convert.ToInt16(dr["Length"].ToString()));
                        columnsToAdd.Add(colToAdd);
                        break;
                    }
                }
            }

            dBHandler.AddColumnToTable(functionDataTableName, columnsToAdd);
        }
        private void AlterFunctionStatusTable()
        {
            var dBHandler = new DBHandler();
            string[] currentColumn = dBHandler.GetCurrentTableColumns(functionStatusTableName);
            string[] serverColumn = columnNames;
            var columnsToAdd = new List<FunctionDataTableColumn>();

            foreach (var colName in serverColumn)
            {
                if (currentColumn.Contains(colName)) continue;
                FunctionDataTableColumn colToAdd = null;
                foreach (DataRow dr in DsSchema.Tables[0].Rows)
                {
                    if ((string)dr["FieldName"] == colName)
                    {
                        colToAdd = new FunctionDataTableColumn(colName, "INT4", 1);
                        columnsToAdd.Add(colToAdd);
                        break;
                    }
                }
            }

            dBHandler.AddColumnToTable(functionStatusTableName, columnsToAdd);
        }

        private void ProvideDefaultLayout()
        {
            var dBHandler = new DBHandler();
            var dsToSave = dBHandler.GetEmptyDataSet(layoutTableName);
            DataSet dsLayout = dBHandler.SelectSimple(layoutTableName);
            if (dsLayout.Tables[0].Rows.Count == 0)
            {
                for (int i = 0; i < DsSchema.Tables[0].Rows.Count; i++)
                {

                    var dr = dsToSave.Tables[0].NewRow();

                    var currentFieldName = DsSchema.Tables[0].Rows[i]["FieldName"].ToString();
                    
                    //Exclude EIS System Fields
                    if (currentFieldName == EISConstant.EISJavaServerMainID) continue;
                    if (currentFieldName == EISConstant.EISTimeStamp) continue;
                    if (currentFieldName == EISConstant.EISSFObjID) continue;
                    dr[0] = currentFieldName;
                    dr[1] = i;

                    dsToSave.Tables[0].Rows.Add(dr);
                }
            }
            dBHandler.InsertRecords(layoutTableName, dsToSave.Tables[0]);

        }


    }
}
